package com.wen.shirodemo;

import com.wen.shirodemo.realm.CustomerMD5Realm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

/**
 * 测试md5加密情况
 */
public class TestMD5RealmAuthenictor {

    public static void main(String[] args) {
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        CustomerMD5Realm customerMD5Realm = new CustomerMD5Realm();
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("md5");
        //设置散列次数
        md5.setHashIterations(1024);
        customerMD5Realm.setCredentialsMatcher(md5);//这里需要指定加密类型
        defaultSecurityManager.setRealm(customerMD5Realm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("xiaochen","123456");

        try{
           subject.login(usernamePasswordToken);
            System.out.println(subject.isAuthenticated());
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("账号不正确");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码不正确");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("调用异常,请核实");
        }

        if(subject.isAuthenticated()){
            //通过用户验证之后的可以进行授权
            //=================基于角色================
            //判断用户是否具有某个角色
            System.out.println("用户权限：：："+subject.hasRole("admin"));
            //判断用户是否同时具有多个角色
            System.out.println("用户权限：：："+subject.hasAllRoles(Arrays.asList("admin", "user")));

            //判断用户是否具有列表中的某个角色
            boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "user"));
            for (int i = 0; i < booleans.length; i++) {
                System.out.println("第"+i+"权限为"+booleans[i]);
            }
//            System.out.println("用户权限：：："+);


            //==================基于资源权限资源校验==============

            System.out.println("资源权限"+subject.isPermitted("user:*:01"));

        }
    }
}
